package com.yjt.fresh.activity;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.api.ApiAddAddress;
import com.yjt.fresh.api.ApiDeleteAddress;
import com.yjt.fresh.api.ApiUpdateAddress;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanAddress;
import com.yjt.fresh.bean.BeanProductDetail;
import com.yjt.fresh.bean.JsonBean;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.utils.GetJsonDataUtil;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.CustomToast;
import com.yjt.fresh.widget.CustomToastResult;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.PreferenceChangeEvent;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 地址详情页
 * Created by mcc on 2018-08-01.
 */

public class AtyAppendAddress extends BaseSimpleActivity {
    @BindView(R.id.rlBack)
    RelativeLayout mRlBack;
    @BindView(R.id.etAppAtyAddAddressName)
    EditText mEtName;
    @BindView(R.id.etAppAtyAddAddressPhone)
    EditText mEtPhone;
    @BindView(R.id.tvAppAtyAddAddressArea)
    TextView mTvArea;
    @BindView(R.id.rlAppAtyAddAddressArea)
    RelativeLayout mRlArea;
    @BindView(R.id.etAppAtyAddAddressDetail)
    EditText mEtDetail;
    @BindView(R.id.btnAppAtyAddAddressSubmit)
    Button mBtnSubmit;
    @BindView(R.id.btnAppAtyAddAddressDelete)
    Button mBtnDelete;
    @BindView(R.id.tvAppAtyAddAddressTitle)
    TextView mTvTitle;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private int addOrUpdate;
    private BeanAddress mAddress;
    private String mProvince;
    private String mCity;
    private String mArea;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_add_address;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        addOrUpdate = getIntent().getIntExtra(MyConstants.ADD_OR_UPDATE_ADDRESS, 0);
        if (addOrUpdate == MyConstants.ADD){
            mTvTitle.setText("新增收货地址");
        }else if (addOrUpdate == MyConstants.UPDATE){
            mBtnDelete.setVisibility(View.VISIBLE);
            mTvTitle.setText("编辑收货地址");
            BeanAddress address = (BeanAddress) getIntent().getSerializableExtra(MyConstants.ADDRESS_OBJ);
            mAddress = address;
            mEtName.setText(address.getRECEIVER_NAME());
            mEtPhone.setText(address.getRECEIVER_PHONE());
            mEtDetail.setText(address.getRECEIVER_ADDRESS());
            mTvArea.setText(address.getPROVINCE()+" "+ address.getCITY()+" "+ address.getAREA());
        }
    }

    @Override
    protected void initEvent() {
        mRlArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initAreaData();
            }
        });

        mBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mEtName.getText().toString())){
                    CustomToast.showLong("请填写收货人");
                    return;
                }
                if (TextUtils.isEmpty(mEtPhone.getText().toString())){
                    CustomToast.showLong("请填写收货人号码");
                    return;
                }
                if (!CommonsToolsHelper.isPhoneNum(mEtPhone.getText().toString())){
                    CustomToast.showLong("请填写正确的手机号码");
                    return;
                }
                if ("点击选择省市区".equals(mTvArea.getText().toString())){
                    CustomToast.showLong("请选择省市区");
                    return;
                }
                if (TextUtils.isEmpty(mEtDetail.getText().toString())){
                    CustomToast.showLong("请填写详细地址");
                    return;
                }

                if (addOrUpdate != 0 && addOrUpdate == MyConstants.ADD) {
                    submitAddress();
                }

                if (addOrUpdate != 0 && addOrUpdate == MyConstants.UPDATE){
                    updateAddress();
                }
            }
        });

        mBtnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteAddress();
            }
        });
        mRlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    HttpOnNextListener<BaseResultEntity> mUpdateListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("修改成功");
            finish();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };
    private void updateAddress() {
        ApiUpdateAddress apiUpdateAddress = new ApiUpdateAddress(mUpdateListener,mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        String[] areas = mTvArea.getText().toString().split(" ");
        map.put("SHIPPINGADDRESS_ID",mAddress.getSHIPPINGADDRESS_ID());
        map.put("RECEIVER_NAME",mEtName.getText().toString());
        map.put("RECEIVER_PHONE",mEtPhone.getText().toString());
        map.put("PROVINCE",areas[0]);
        map.put("CITY",areas[1]);
        map.put("AREA",areas[2]);
        map.put("RECEIVER_ADDRESS",mEtDetail.getText().toString());
        map.put("IS_DEFAULT",mAddress.getIS_DEFAULT());
        map.put("SESSION_ID",PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiUpdateAddress.setMap(map);

        HttpManager.getInstance().doHttpDeal(apiUpdateAddress);
    }

    HttpOnNextListener<BaseResultEntity> mDeleteListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("删除成功");
            finish();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };
    private void deleteAddress() {
        ApiDeleteAddress apiDeleteAddress = new ApiDeleteAddress(mDeleteListener,mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        map.put("SHIPPINGADDRESS_ID",mAddress.getSHIPPINGADDRESS_ID());
        map.put("SESSION_ID",PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiDeleteAddress.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiDeleteAddress);
    }

    HttpOnNextListener<BaseResultEntity> mAddListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("新增成功");
            finish();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };
    private void submitAddress() {
        ApiAddAddress apiAddAddress = new ApiAddAddress(mAddListener,mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        String[] areas = mTvArea.getText().toString().split(" ");
        map.put("RECEIVER_NAME",mEtName.getText().toString());
        map.put("RECEIVER_PHONE",mEtPhone.getText().toString());
        map.put("PROVINCE",areas[0]);
        map.put("CITY",areas[1]);
        map.put("AREA",areas[2]);
        map.put("RECEIVER_ADDRESS",mEtDetail.getText().toString());
        map.put("IS_DEFAULT","0");
        map.put("SESSION_ID",PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiAddAddress.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiAddAddress);
    }

    private void initAreaData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        showPickerView();

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                mProvince = options1Items.get(options1).getPickerViewText();
                mCity = options2Items.get(options1).get(options2);
                mArea = options3Items.get(options1).get(options2).get(options3);
                String tx = mProvince +
                        " " + mCity +
                        " " + mArea;
                mTvArea.setText(tx);


            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }
}
